<?php

namespace app\api\controller\meiriyiwen;

use app\admin\model\MeiriDbfm;
use app\admin\model\MeiriKaiyan;
use app\api\controller\Base;
use app\api\controller\Utils;
use think\cache\driver\Redis;
use think\Db;
use think\Exception;
use think\Request;

/**
 * 媒体素材接口
 */
class Medias extends Base
{

    public $util;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->util = new Utils();
    }

    // 配置
    public function config()
    {
        $v = $this->request->param('v');
        $videoflag = true;
        $musicflag = true;

        if ($v == '0.0.0') {
            $videoflag = false;
            $musicflag = false;
        }

        $flags = array(
            'videoflag' => $videoflag,
            'musicflag' => $musicflag,
        );

        $this->result('flag', $flags);
    }

    // 爬取视频
    public function get_video($url = 'http://baobab.kaiyanapp.com/api/v4/tabs/selected')
    {
        $res = $this->http($url);
        $json = json_decode($res, true);
        $list = $json['itemList'];
        if (count($list)) {
            foreach ($list as $item) {
                if ($item['type'] != 'video') {
                    continue;
                }
                $info['type'] = $item['type'];

                $data = $item['data'];
                if (!array_key_exists('playUrl', $data)) {
                    continue;
                }

                $info['title'] = array_key_exists('title', $data) ? $data['title'] : '';
                $info['desc'] = array_key_exists('description', $data) ? $data['description'] : '';
                $info['cover'] = array_key_exists('cover', $data) ? $data['cover']['feed'] : '';
                $info['play_url'] = array_key_exists('playUrl', $data) ? $data['playUrl'] : '';
                $info['duration'] = array_key_exists('duration', $data) ? $this->util->sec_to_time($data['duration']) : '';
                $info['date'] = array_key_exists('date', $data) ? $data['date'] : '';
                $info['createtime'] = time();
                $info['updatetime'] = time();

                Db::name('meiri_kaiyan')->insert($info);
            }
        }
        $next_url = $json['nextPageUrl'];
        $this->result('', $next_url);
    }

    // 爬取音频
    public function get_music()
    {
        $url = 'https://douban.fm/j/v2/playlist';
        $params['channel'] = '-10';
        $params['app_name'] = 'radio_website';
        $params['version'] = '100';
        $params['type'] = 's';
        $params['sid'] = mt_rand();

        $cookie = $this->get_douban_cookie();

        $res = $this->http($url, $params, 'GET', $cookie);
        $data = json_decode($res);
        $songs = $data->song;

        if (count($songs)) {
            foreach ($songs as $song) {
                if (!$song->url) {
                    continue;
                }
                $fm = new MeiriDbfm();
                $fm->title = $song->title;
                $fm->artist = $song->artist;
                $fm->cover = $song->picture;
                $fm->url = $song->url;
                $fm->duration = $this->util->sec_to_time($song->length);
                $fm->save();
            }
        }

        return 'ok';
    }

    // 查询单独音频
    public function query_music()
    {
        $id = $this->request->param('id');
        // 有指定id就拿,没有就随机一个
        if ($id) {
            $song = MeiriDbfm::get($id);
            $this->result('music', $song);
        }
        $this->get_music();
        $song = $this->util->get_rand(1, 'meiri_dbfm');
        $this->result('music', $song[0]);
    }

    // 获取媒体列表
    public function get_media_list()
    {
        $video_list = $this->util->get_rand(4, 'meiri_kaiyan');
        $this->result('video', $video_list);
    }

    // 查询单独视频
    public function query_video()
    {
        $id = $this->request->param('id');
        $video = MeiriKaiyan::get($id);
        $this->result('video', $video);
    }

    // 获取豆瓣fm cookie
    public function get_douban_cookie()
    {
        $redis = new Redis();
        $cookie = $redis->get('douban_cookie');
        if (!$cookie) {
            $url = 'https://douban.fm/j/v2/playlist';
            $params['channel'] = '-10';
            $params['app_name'] = 'radio_website';
            $params['version'] = '100';
            $params['type'] = 's';
            $params['sid'] = mt_rand();

            $res = $this->http($url, $params, 'GET', '', true);

            $preg_cookie = '/Set-Cookie: (.*?);/m';
            if (preg_match_all($preg_cookie, $res, $cookie)) {
                $cookie = implode(';', $cookie['1']);
            }

            $redis->set('douban_cookie', $cookie);
        }
        return $cookie;
    }

    // http
    public function http($url, $params = [], $method = 'GET', $cookie = '', $need_header = false, $header = array(), $multi = false)
    {
        $opts = array(
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => $header
        );

        // 返回header
        if ($need_header) {
            $opts[CURLOPT_HEADER] = true;
        }

        /* cookie */
        if ($cookie) {
            $opts[CURLOPT_COOKIE] = $cookie;
        }

        /* 根据请求类型设置特定参数 */
        switch (strtoupper($method)) {
            case 'GET':
                if (empty($params)) {
                    $opts[CURLOPT_URL] = $url;
                } else {
                    $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                }
                break;
            case 'POST':
                // 判断是否传输文件
//                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                throw new Exception('不支持的请求方式');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if ($error) throw new Exception('请求发生错误; ' . $error);
        return $data;
    }
}
